<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        充电站详情<span>{{
          priceFormVisible ? '' : '(该账号只能创建免费电站，请开通收费功能)'
        }}</span>
      </div>
      <i-form
        ref="baseForm"
        :items="baseFormItems"
        :model="baseForm"
        :label-width="200"
        label-position="left"
        :rules="baseFormRules"
      >
        <template slot="address">
          <el-form-item class="is-required" label="所属区域：" prop="area">
            <CommonAddressCascader
              ref="area"
              v-model="area"
              :area="designatedArea"
              show-label
            />
          </el-form-item>
        </template>
        <template slot="poi">
          <el-form-item
            label="标注位置:"
            class="is-required"
            prop="checkedPoint"
          >
            <el-button
              icon="el-icon-location-outline"
              type="primary"
              @click="showMap"
              >标注位置</el-button
            >
            <div v-if="checkedPoint" class="show-tip">
              <i class="el-icon-check"></i>位置已标注
            </div>
          </el-form-item>
        </template>
        <template slot="picture">
          <el-form-item label="图片(注：正方形图片)：" prop="stationImg">
            <hyc-form-upload
              ref="stationImg"
              v-model="baseForm.stationImg"
              :upload-data="stationImgData"
              :show-cropper="true"
            >
            </hyc-form-upload>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel">
      <div class="panel-header">收费标准</div>
      <i-form
        ref="priceForm"
        :items="priceFormItems"
        :model="priceForm"
        :label-width="200"
        label-position="left"
        :rules="priceFormRules"
      >
        <template slot="staPriceType">
          <el-form-item class="is-required" label="计费模式：">
            <el-radio-group
              v-model="priceForm.staPriceType"
              @change="handleStaPriceType"
            >
              <el-radio label="DURATION">按照阶梯功率计费 </el-radio>
              <!-- <el-radio
                label="INTERVAL"
                :disabled="priceForm.payType === 'PostPay'"
                >按照区间电价计费
              </el-radio> -->
              <!-- <el-radio
                label="FIXED"
                :disabled="priceForm.payType === 'PostPay'"
                >按照固定价格计费
              </el-radio> -->
            </el-radio-group></el-form-item
          >
        </template>
        <template slot="power">
          <el-form-item class="is-required" label="功率(W)：">
            <div class="power-wrapper">
              <div class="power-input">
                <div
                  class="power-input__item"
                  v-for="(item, index) in powerArr"
                  :key="index"
                >
                  <el-input disabled v-model="item.start"></el-input>
                  <div class="line"></div>
                  <el-input
                    class="v-validate"
                    :disabled="index === powerArr.length - 1"
                    v-model="item.end"
                    v-validate="integerRules"
                    @input="handleInput(item, index)"
                  ></el-input>
                  <el-input
                    class="v-validate"
                    v-validate="powerPriceRules"
                    v-model="item.price"
                  ></el-input
                  >元/小时
                </div>
              </div>
              <div class="btn">
                <i
                  class="el-icon-remove"
                  v-if="powerArr.length > 1"
                  @click="deletePower"
                ></i>
                <i
                  class="el-icon-circle-plus"
                  v-if="powerArr.length < 8"
                  @click="addPower"
                ></i>
              </div>
            </div>
            <div class="item-tip">
              最多设置8个功率，最少设置一个功率，功率大的单价不能小于小功率的单价
            </div>
          </el-form-item>
        </template>
        <template slot="duration" v-if="priceForm.stationChargeTime">
          <el-form-item
            class="duration-item"
            label="充电时长配置："
            prop="stationChargeTime"
          >
            <div>
              <el-checkbox-group
                v-model="priceForm.stationChargeTime"
                :min="1"
                :max="5"
                @change="handelSelect"
              >
                <el-checkbox-button
                  v-for="duration in durationArr"
                  :label="duration"
                  :key="duration"
                  >{{ duration }}小时</el-checkbox-button
                >
              </el-checkbox-group>
            </div>
            <div class="item-tip">
              请选择1-5个充电时长，自定义时长选项用户可以随意选择所选最大值以内某一充电时长。建议选择5个时长（1、2、4、6、8小时）
            </div>
          </el-form-item>
        </template>
        <template slot="price">
          <el-form-item class="is-required" label="价格：">
            <div class="power-wrapper">
              <div class="power-input">
                <div
                  class="power-input__item"
                  v-for="(item, index) in priceArr"
                  :key="index"
                >
                  <el-time-select
                    disabled
                    placeholder="开始时间"
                    v-model="item.startTime"
                  >
                  </el-time-select>
                  <div class="line"></div>
                  <el-time-select
                    class="v-validate"
                    v-validate="timeEndRules"
                    :disabled="index === priceArr.length - 1"
                    @change="handelTimeInput(item, index)"
                    placeholder="结束时间"
                    v-model="item.endTime"
                    :picker-options="{
                      start: '00:00',
                      step: '00:60',
                      end: '23:00',
                      minTime: item.startTime,
                    }"
                  >
                  </el-time-select>
                  <el-input
                    class="v-validate"
                    v-validate="sectionPriceRules"
                    v-model="item.price"
                    v-if="priceForm.staPriceType != 'INTERVAL'"
                  ></el-input>
                  <el-input
                    class="v-validate"
                    v-validate="sectionPriceRulesFour"
                    v-model="item.price"
                    v-if="priceForm.staPriceType == 'INTERVAL'"
                  ></el-input>
                  元/度
                </div>
              </div>
              <div class="btn">
                <i
                  class="el-icon-remove"
                  v-if="priceArr.length > 1"
                  @click="deletePrice"
                ></i>
                <i
                  class="el-icon-circle-plus"
                  v-if="priceArr.length < 9"
                  @click="addPrice"
                ></i>
              </div>
            </div>
          </el-form-item>
        </template>
        <template slot="money" v-if="priceForm.quotaPrice">
          <el-form-item
            class="duration-item"
            label="预付金额配置："
            prop="quotaPrice"
          >
            <div>
              <el-checkbox-group
                v-model="priceForm.quotaPrice"
                :min="1"
                :max="6"
                @change="handelSelect"
              >
                <el-checkbox-button
                  v-for="money in moneyArr"
                  :label="money"
                  :key="money"
                  >{{ money }}元</el-checkbox-button
                >
              </el-checkbox-group>
            </div>
            <div class="item-tip">
              请选择1-6个预付金额，建议选择4个价格（1、2、4、8元）
            </div>
          </el-form-item>
        </template>
        <template slot="serviceType">
          <el-form-item class="is-required" label="服务费配置：">
            <el-radio-group
              v-model="priceForm.serviceType"
              @change="handleServiceType"
            >
              <el-radio label="AccordingToTimes">按每次充电计费 </el-radio>
              <el-radio label="AccordingToDuration" disabled
                >按每小时充电计费
              </el-radio>
              <el-radio
                label="AccordingToQuantity"
                :disabled="
                  priceForm.payType === 'PostPay' ||
                  this.priceForm.staPriceType === 'DURATION'
                "
                >按每度充电计费
              </el-radio>
            </el-radio-group></el-form-item
          >
        </template>
        <template slot="timecard">
          <el-form-item
            class="timecard-item"
            :class="{ 'is-required': timecardVisible }"
            label="时长卡规则："
          >
            <el-button v-if="!timecardVisible" @click="handleAddTimeCard"
              >添加时长卡规则</el-button
            >
            <div v-if="timecardVisible" class="timecard-wrapper">
              <div class="timecard-input">
                <div
                  class="timecard-input__item"
                  v-for="(item, index) in timecardArr"
                  :key="index"
                >
                  <div class="timecard-input__cell">
                    请输入时长卡期限
                    <el-input
                      class="v-validate"
                      v-model.number="item.availableDay"
                      placeholder="无限"
                      v-validate="periodRules"
                    ></el-input>
                    天，
                  </div>
                  <div class="timecard-input__cell">
                    时长卡时间
                    <el-input
                      v-model.number="item.hour"
                      class="v-validate"
                      v-validate="hourRules"
                    ></el-input>
                    小时，
                  </div>
                  <div class="timecard-input__cell">
                    <el-input
                      v-model="item.price"
                      class="v-validate"
                      v-validate="timecardRules"
                    ></el-input>
                    元
                  </div>
                </div>
              </div>
              <div class="btn">
                <i class="el-icon-remove" @click="deleteTimecard"></i>
                <i
                  class="el-icon-circle-plus"
                  v-if="timecardArr.length < 8"
                  @click="addTimecard"
                ></i>
              </div>
            </div>
            <div class="item-tip">
              推荐设置价格25元，包含100小时，至多建立八种
            </div>
          </el-form-item>
        </template>
        <template slot="isFloor" v-if="timecardVisible">
          <el-form-item class="is-required" label="时长卡是否按阶梯收费">
            <el-col style="line-height: 32px" :span="13">
              <div class="timecard-charging">
                <el-radio-group v-model="priceForm.timecardPowerCharging">
                  <el-radio :label="true">是</el-radio>
                  <el-radio :label="false">否</el-radio>
                </el-radio-group>
                <img
                  class="timecard-charging__img"
                  @click="handleShowTips"
                  src="@/assets/images/helpIcon.png"
                />
              </div>
            </el-col>
          </el-form-item>
        </template>
        <template slot="fixedPrice">
          <el-form-item label="价格：" prop="fixedPrice">
            <div
              class="fixedPrice-wrapper"
              v-for="(item, index) in fixedPriceArr"
              :key="index"
            >
              <div class="fixedPrice__item">
                <el-input
                  class="fixedPrice-input-price v-validate"
                  v-model="item.price"
                  v-validate="fixedPriceRules"
                ></el-input
                >元
                <div class="fixedPrice-input-power">
                  <div>
                    <div
                      class="power-input__item"
                      v-for="(itemChild, indexChild) in item.powerArr"
                      :key="indexChild"
                    >
                      <el-input disabled v-model="itemChild.start"></el-input>
                      <div class="line"></div>
                      <el-input
                        class="v-validate power-end"
                        :disabled="indexChild === item.powerArr.length - 1"
                        v-model="itemChild.end"
                        v-validate="integerRules"
                        @input="handlePowerInput(itemChild, indexChild, index)"
                      ></el-input>
                      <el-input
                        class="v-validate"
                        v-validate="fixedHourRules"
                        v-model="itemChild.duration"
                      ></el-input
                      >小时
                    </div>
                  </div>
                  <div class="btn">
                    <i
                      class="el-icon-remove"
                      v-if="item.powerArr.length > 1"
                      @click="deletePricePower(index)"
                    ></i>
                    <i
                      class="el-icon-circle-plus"
                      v-if="item.powerArr.length < 4"
                      @click="addPricePower(index)"
                    ></i>
                  </div>
                </div>
              </div>
              <div>
                <i
                  class="el-icon-circle-plus"
                  @click="addFixedPrice"
                  v-if="
                    fixedPriceArr.length - 1 == index &&
                    fixedPriceArr.length < 4
                  "
                >
                </i>
                <i class="el-icon-delete" @click="deleteFixedPrice(index)"> </i>
              </div>
            </div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="description-statement">
      说明：刷卡式充电设备以充满自停的方式充电，充电费用不能超过余额。充电费用按照和能量、卡上余额的优先级进行抵扣。
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" @click="handleOk" v-checkSubmit>确认</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>
    <MapDlg
      ref="mapDlg"
      :visible.sync="mapVisible"
      title="标注地理位置"
      :defaultPoint="defaultPoint"
      @submit="submitMap"
    />
    <PowerChargingTip :visible.sync="tipsVisible" />
  </div>
</template>
<script>
import Big from 'big.js'
import _ from 'lodash'
import { checkUserCash, createStation, stationDetail } from '@/api/device'
import CommonAddressCascader from '@/components/CommonAddressCascader'
import MapDlg from '@/components/MapDlg'
import HycFormUpload from '@/components/hycFormUpload'
import PowerChargingTip from '@/components/PowerChargingTip'
import { aMapLoader, toAMapLngLat, toBdMapLngLat } from '@/utils/aMapApi'
import { isString } from 'lodash'
import { validateMap } from '@/utils/validate'
import formValidate from '@/utils/validate'
import { typeMap } from '@/utils/format'
export default {
  name: 'StationAdd',
  components: {
    CommonAddressCascader,
    HycFormUpload,
    MapDlg,
    PowerChargingTip,
  },
  data() {
    return {
      isElectricServicePrice: false, //按度收服务费
      isTimesServicePrice: true, //默认按每次充电计费
      isDurationServicePrice: false, //按每小时充电计费
      powerStartCurrent: '',
      area: [],
      designatedArea: ['广东省'],
      designatedAreaLength: 6,
      baseForm: {
        stationImg: '',
        hasRemark: false,
      },
      mapVisible: false,
      pictureVisible: false,
      timecardVisible: false,
      defaultPoint: {},
      checkedPoint: null,
      durationArr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      moneyArr: [1, 2, 3, 4, 5, 6, 7, 8],
      stationImgData: { fileType: 'IMAGE' },
      priceFormVisible: false,
      tipsVisible: false,
      type: ['add', 'edit', 'copy']
        .filter((item) => this.$route.path.includes(item))
        .join(),
      powerArr: [
        {
          start: '0',
          end: '最大功率',
          price: '',
        },
      ],
      priceArr: [
        {
          startTime: '00:00',
          endTime: '24:00',
          price: '',
        },
      ],
      timecardArr: [],
      tempObj: {
        stationChargeTime: [],
        quotaPrice: [],
      },
      fixedPriceArr: [
        {
          price: '',
          powerArr: [
            {
              start: '0',
              end: '最大功率',
              duration: '',
            },
          ],
        },
      ],
      baseFormItems: [
        {
          type: 'text',
          label: '充电站名称：',
          value: 'stationName',
          required: true,
          maxlength: 30,
          showWordLimit: true,
        },
        {
          slot: 'address',
        },
        {
          type: 'text',
          label: '所属小区：',
          value: 'remark',
          maxlength: 30,
          showWordLimit: true,
          clearable: true,
          ifRender: (data) => {
            return data.hasRemark
          },
        },
        {
          type: 'textarea',
          label: '详细位置：',
          value: 'stationAddress',
          maxlength: 100,
          clearable: true,
          required: true,
          showWordLimit: true,
        },
        {
          slot: 'poi',
        },
        {
          slot: 'picture',
        },
        {
          type: 'text',
          label: '电站管理员电话：',
          value: 'customerServicePhone',
          required: true,
        },
        {
          type: 'text',
          label: '电费成本信息（元）：',
          value: 'electcost',
          required: true,
        },
      ],
      priceForm: {
        serviceType: 'AccordingToTimes',
        payType: 'PostPay',
        stationType: 'MIX',
        staPriceType: 'DURATION',
        quotaPrice: [],
        stationChargeTime: [],
      },
      priceFormItems: [
        {
          type: 'radio',
          value: 'payType',
          options: [
            {
              text: '后付费',
              label: 'PostPay',
            },
            {
              text: '预付费',
              label: 'PrePay',
            },
          ],
          change: this.handlePayType,
          ifRender: () => {
            return this.priceFormVisible
          },
        },
        {
          type: 'select',
          label: '电站类型：',
          value: 'stationType',
          options: typeMap.selectOptions(['NO_TYPE'], 'stationType'),
          disabled: () => !this.priceFormVisible,
          required: true,
          change: this.handleStation,
        },
        {
          slot: 'staPriceType',
          ifRender: () => {
            return this.priceForm.stationType !== 'FREE'
          },
        },
        {
          slot: 'power',
          ifRender: () => {
            return (
              this.priceForm.stationType !== 'FREE' &&
              this.priceForm.staPriceType === 'DURATION'
            )
          },
        },
        {
          slot: 'duration',
          value: 'stationChargeTime',
          required: true,
          ifRender: () => {
            return this.priceForm.staPriceType === 'DURATION'
          },
        },
        {
          slot: 'price',
          value: 'quotaPrice',
          required: true,
          ifRender: () => {
            return (
              this.priceForm.stationType !== 'FREE' &&
              this.priceForm.staPriceType === 'INTERVAL'
            )
          },
        },
        {
          slot: 'money',
          required: true,
          ifRender: () => {
            return (
              this.priceForm.stationType !== 'FREE' &&
              this.priceForm.staPriceType === 'INTERVAL'
            )
          },
        },
        {
          slot: 'serviceType',
          required: true,
          ifRender: () => {
            return (
              this.priceForm.stationType !== 'FREE' &&
              (this.priceForm.staPriceType === 'INTERVAL' ||
                this.priceForm.staPriceType === 'DURATION')
            )
          },
        },
        {
          slot: 'fixedPrice',
          required: true,
          ifRender: () => {
            return (
              this.priceForm.stationType !== 'FREE' &&
              this.priceForm.staPriceType === 'FIXED'
            )
          },
        },
        {
          type: 'text',
          label: '服务费（元）：',
          value: 'stationService',
          required: true,
          ifRender: () => {
            return this.priceForm.stationType !== 'FREE'
          },
        },
        {
          slot: 'timecard',
          ifRender: () => {
            return (
              (this.priceForm.stationType === 'MONTHLY' ||
                this.priceForm.stationType === 'MIX') &&
              this.priceForm.staPriceType === 'DURATION'
            )
          },
        },
        {
          slot: 'isFloor',
          required: true,
          value: 'timecardPowerCharging',
          ifRender: () => {
            return (
              (this.priceForm.stationType === 'MONTHLY' ||
                this.priceForm.stationType === 'MIX') &&
              this.priceForm.staPriceType === 'DURATION'
            )
          },
        },
      ],
      integerRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePositiveInteger,
        {
          validator: (val) => {
            return val <= 2200
          },
          msg: '不能大于2200！',
        },
        {
          validator: (val) => {
            return (
              !this.powerStartCurrent || parseInt(this.powerStartCurrent) < val
            )
          },
          msg: '不能小于或者等于起始值',
        },
      ],
      powerPriceRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecision,
      ],
      sectionPriceRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecisionOne,
      ],

      sectionPriceRulesFour: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecisionOneFour,
      ],

      hourRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePositiveInteger,
        {
          validator: (val) => {
            return val <= 8640
          },
          msg: '不能大于8640！',
        },
      ],
      timecardRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecisionTwo,
        {
          validator: (val) => {
            return val <= 999
          },
          msg: '不能大于999！',
        },
      ],
      timeEndRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
      ],
      periodRules: [
        {
          validator: (value) => {
            if (value) {
              let reg = /^[7-9]$|^[1-9]\d+$/
              return reg.test(value) && parseInt(value) <= 999
            }
            return true
          },
          msg: '不能小于7天且不能大于999',
        },
      ],
      fixedPriceRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecisionThree,
      ],
      fixedHourRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validateHour,
      ],
      baseFormRules: {
        stationName: [
          {
            validator: formValidate('validateAdministrator'),
            trigger: ['change', 'blur'],
          },
        ],
        area: [
          {
            validator: (rule, value, callback) => {
              if (!this.area || this.area.length === 0) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
          },
        ],
        checkedPoint: [
          {
            validator: (rule, value, callback) => {
              if (!this.checkedPoint) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
          },
        ],
        stationImg: [
          {
            required: true,
            message: '该项为必填项',
          },
        ],
        customerServicePhone: [
          {
            validator: formValidate('validateServiceMobile'),
            trigger: ['change', 'blur'],
          },
        ],
        stationChargeTime: [
          {
            required: true,
            message: '该项为必填项',
            trigger: ['change', 'blur'],
          },
        ],
        electcost: [
          {
            validator: formValidate('validatePrecisionOne'),
            trigger: ['change', 'blur'],
          },
        ],
      },
      priceFormRules: {
        stationService: [
          {
            validator: formValidate('validatePrecisionOne'),
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },
  watch: {
    area(val) {
      if (this.dirtyArea) {
        this.dirtyArea = false
        return
      }
      this.baseForm.hasRemark =
        this.designatedArea &&
        this.designatedArea.length &&
        val &&
        val.length === this.designatedAreaLength //选到6级地址
      this.checkedPoint = null
    },
    'baseForm.stationAddress'(val, oldVal) {
      if ((!val || val !== oldVal) && oldVal !== undefined) {
        this.checkedPoint = null
      }
    },
    checkedPoint() {
      this.$refs.baseForm.validateField('checkedPoint')
    },
    'priceForm.staPriceType'(val) {
      val === 'INTERVAL'
        ? this.$set(this.priceForm, 'quotaPrice', [...this.tempObj.quotaPrice])
        : this.$set(this.priceForm, 'stationChargeTime', [
            ...this.tempObj.stationChargeTime,
          ])
    },
  },
  created() {
    checkUserCash().then((res) => {
      this.priceFormVisible = res
      this.priceForm = {
        ...this.priceForm,
        stationType: res ? 'MIX' : 'FREE',
        payType: res ? 'PostPay' : null,
      }
      if (this.$route.params.id) {
        stationDetail({ id: this.$route.params.id }).then((res) => {
          this.dirtyArea = true
          this.detailData = res
          this.handleBackFill()
        })
      }
    })
  },
  methods: {
    _goToCreateAndEnergy() {
      this.$confirm(
        '如果您创建了套餐电站，但未设置时长卡规则，也未创建通用时长卡或和能量，用户将无法充电',
        '提示',
        {
          confirmButtonText: '创建和能量',
          cancelButtonText: '取消',
          center: true,
          customClass: 'tip-dialog__wrapper',
        }
      )
        .then(() => {
          this.$router.push('/myself/andEnergyAdd')
        })
        .catch((err) => console.log(err))
    },
    handlePayType(val) {
      console.log(val)
      val === 'PostPay' ? (this.priceForm.staPriceType = 'DURATION') : null
    },
    handleStaPriceType(val) {
      switch (val) {
        case 'DURATION': // 按照阶梯功率计费
          this.$set(this.priceForm, 'serviceType', 'AccordingToTimes')
          this.isElectricServicePrice = false
          this.isTimesServicePrice = true
          this.isDurationServicePrice = false
          break
        default:
          break
      }
    },
    handleServiceType(val) {
      switch (val) {
        case 'AccordingToQuantity': // 按每度充电计费
          this.isElectricServicePrice = true
          this.isTimesServicePrice = false
          this.isDurationServicePrice = false
          break
        case 'AccordingToTimes': // 按每次充电计费
          this.isElectricServicePrice = false
          this.isTimesServicePrice = true
          this.isDurationServicePrice = false
          break
        case 'AccordingToDuration': // 按每小时充电计费
          this.isElectricServicePrice = false
          this.isTimesServicePrice = false
          this.isDurationServicePrice = true
          break
      }
    },
    handleStation(val) {
      val === 'FREE'
        ? (this.powerArr = [
            {
              start: '0',
              end: '最大功率',
              price: '',
            },
          ])
        : null
      this.timecardVisible && (val === 'MIX' || val === 'MONTHLY')
        ? this.$set(this.priceForm, 'timecardPowerCharging', false)
        : null
    },
    handelSelect(val) {
      this.priceForm.staPriceType === 'INTERVAL'
        ? (this.tempObj.quotaPrice = val)
        : (this.tempObj.stationChargeTime = val)
    },
    async handleBackFill() {
      //复制和新增两种状态下数据回填
      this.baseForm = {
        customerServicePhone: this.detailData.customerServicePhone,
        electcost: this.detailData.electcost,
      }
      if (this.type === 'edit') {
        //只限制编辑状态下回填
        this.baseForm = {
          ...this.baseForm,
          stationName: this.detailData.stationName,
          stationAddress: this.detailData.stationAddress,
          stationImg: this.detailData.stationImg,
          remark: this.detailData.remark,
        }
        let aMapLngLat = await toAMapLngLat({
          lng: this.detailData.stationLng,
          lat: this.detailData.stationLat,
        })
        this.checkedPoint = {
          lat: aMapLngLat.lat,
          lng: aMapLngLat.lng,
        }
        this.area = [
          `${this.detailData.province},${this.detailData.provinceName}`,
          `${this.detailData.city},${this.detailData.cityName}`,
          `${this.detailData.district},${this.detailData.districtName}`,
        ]
        //处理选择六级地址情况
        if (
          this.detailData.defAdCodeCodePath &&
          this.detailData.defAdCodeNamePath
        ) {
          let defAdCodeNamePath = this.detailData.defAdCodeNamePath.split(',')
          defAdCodeNamePath.splice(0, defAdCodeNamePath.length === 5 ? 2 : 3)
          let defAdCodeCodePath = this.detailData.defAdCodeCodePath.split(',')
          defAdCodeCodePath.splice(0, defAdCodeCodePath.length === 5 ? 2 : 3)
          defAdCodeCodePath.forEach((item, index) => {
            this.area.push(`${item},${defAdCodeNamePath[index]}`)
          })
          this.baseForm.hasRemark = true
          // this.baseForm.remark = this.detailData.remark
        }
      }
      this.priceForm.stationType = this.detailData.stationType
      if (this.detailData.stationType === 'FREE') {
        this.$set(
          this.priceForm,
          'stationChargeTime',
          this.detailData.stationChargeTime
            .split(',')
            .map((item) => parseInt(item))
        )
        this.tempObj.stationChargeTime = [...this.priceForm.stationChargeTime]
      } else {
        this.priceForm = {
          ...this.priceForm,
          payType: this.detailData.payType,
          staPriceType: this.detailData.staPriceType,
        }
        if (
          this.detailData.electricServicePrice == null ||
          this.detailData.electricServicePrice == 0
        ) {
          if (this.detailData.durationServicePrice > 0) {
            this.$set(
              this.priceForm,
              'stationService',
              this.detailData.durationServicePrice
            )
            this.$set(this.priceForm, 'serviceType', 'AccordingToDuration')
            this.isElectricServicePrice = false
            this.isTimesServicePrice = false
            this.isDurationServicePrice = true
          } else if (this.detailData.stationService > 0) {
            this.$set(
              this.priceForm,
              'stationService',
              this.detailData.stationService
            )
            this.$set(this.priceForm, 'serviceType', 'AccordingToTimes')
            this.isElectricServicePrice = false
            this.isTimesServicePrice = true
            this.isDurationServicePrice = false
          }
        } else {
          if (this.detailData.electricServicePrice > 0) {
            this.$set(
              this.priceForm,
              'stationService',
              this.detailData.electricServicePrice
            )
            this.$set(this.priceForm, 'serviceType', 'AccordingToQuantity')
            this.isElectricServicePrice = true
            this.isTimesServicePrice = false
            this.isDurationServicePrice = false
          }
        }
        if (this.detailData.staPriceType === 'DURATION') {
          this.$set(
            this.priceForm,
            'stationChargeTime',
            this.detailData.stationChargeTime
              .split(',')
              .map((item) => parseInt(item))
          )
          this.tempObj.stationChargeTime = [...this.priceForm.stationChargeTime]
          //阶梯功率
          let powerArr = this.detailData.ladderPower.split(',')
          let priceArr = this.detailData.ladderPrice.split(',')
          this.powerArr = []
          powerArr.forEach((item, index) => {
            this.powerArr.push({
              start: item,
              end:
                index === powerArr.length - 1
                  ? '最大功率'
                  : powerArr[index + 1],
              price: priceArr[index],
            })
          })

          if (
            (this.detailData.stationType === 'MONTHLY' ||
              this.detailData.stationType === 'MIX') &&
            'timecardPowerCharging' in this.detailData
          ) {
            this.$set(
              this.priceForm,
              'timecardPowerCharging',
              this.detailData.timecardPowerCharging
            )
            this.timecardArr = []
            let timecardArr = this.detailData.timeCardRule
              ? this.detailData.timeCardRule.split(';')
              : []
            timecardArr.forEach((item) => {
              let ruleArr = item.split(',')
              ruleArr.length === 2 ? ruleArr.push('') : null
              this.timecardArr.push({
                availableDay: ruleArr[2],
                hour: ruleArr[0],
                price: ruleArr[1],
              })
            })
            this.timecardVisible = !!this.timecardArr.length //编辑状态下有时长卡则显示时长卡
          }
        } else if (this.detailData.staPriceType === 'INTERVAL') {
          //区间电价
          this.$set(
            this.priceForm,
            'quotaPrice',
            this.detailData.quotaPrice.split(',').map((item) => parseInt(item))
          )
          this.tempObj.quotaPrice = [...this.priceForm.quotaPrice]
          let priceDscrptJson = JSON.parse(this.detailData.priceDscrptJson)
          this.priceArr = []
          priceDscrptJson.forEach((item, index) => {
            this.priceArr.push({
              startTime: index === 0 ? '00:00' : priceDscrptJson[index - 1].t,
              endTime: item.t,
              // price: item.pr,
              price: item.ep ? item.ep : item.pr,
            })
          })
        } else if (this.detailData.staPriceType === 'FIXED') {
          let priceDscrptJson = JSON.parse(this.detailData.priceDscrptJson)
          this.fixedPriceArr = []
          priceDscrptJson.forEach((item) => {
            this.fixedPriceArr.push({
              price: item.lpr,
              powerArr: item.spd.map((itemChild, index) => {
                return {
                  start: itemChild.p,
                  end:
                    index === item.spd.length - 1
                      ? '最大功率'
                      : item.spd[index + 1].p,
                  duration: itemChild.t,
                }
              }),
            })
          })
        }
      }
    },
    handleShowTips() {
      this.tipsVisible = true
    },
    showMap() {
      let hasDesignatedArea =
        this.area &&
        !!this.area
          .map((item) => item.split(',')[1])
          .filter((item) => this.designatedArea.indexOf(item) > -1).length
      if (
        ((hasDesignatedArea &&
          this.area.length === this.designatedAreaLength) ||
          (!hasDesignatedArea && this.area.length === 3)) &&
        this.baseForm.stationAddress
      ) {
        let stationAddress = ''
        this.area.forEach((item) => {
          if (isString(item)) {
            stationAddress +=
              item.split(',')[1] === '其他' || !item.split(',')[1]
                ? ''
                : item.split(',')[1]
          }
        })
        stationAddress +=
          (this.baseForm.remark ? this.baseForm.remark : '') +
          this.baseForm.stationAddress
        aMapLoader().then(() => {
          new window.AMap.plugin(['AMap.PlaceSearch'], () => {
            var PlaceSearchOptions = {
              city: this.area[1].split(',')[1], //城市
              pageSize: 10, //每页结果数,默认10
              pageIndex: 1, //请求页码，默认1
              extensions: 'base', //返回信息详略，默认为base（基本信息）
            }
            var MapSearch = new window.AMap.PlaceSearch(PlaceSearchOptions)
            window.AMap.event.addListener(MapSearch, 'complete', (results) => {
              this.mapVisible = true
              this.defaultPoint = this.checkedPoint
                ? this.checkedPoint
                : results.poiList.pois[0].location
            })
            MapSearch.search(stationAddress)
          })
        })
      } else {
        this.$message({
          type: 'error',
          showClose: true,
          message: '请选择完整地址信息，包括省、市、区和具体地址',
        })
      }
    },
    submitMap(point) {
      console.log(point)
      this.checkedPoint = point
    },
    addPower() {
      this.powerArr[this.powerArr.length - 1].end = ''
      this.powerArr.push({
        start: this.powerArr[this.powerArr.length - 1].end,
        end: '最大功率',
        price: '',
      })
    },
    deletePower() {
      this.powerArr.pop()
      this.powerArr[this.powerArr.length - 1].end = '最大功率'
    },
    addPricePower(index) {
      let powerArr = this.fixedPriceArr[index].powerArr
      this.fixedPriceArr[index].powerArr[powerArr.length - 1].end = ''
      this.fixedPriceArr[index].powerArr.push({
        start: this.fixedPriceArr[index].powerArr[powerArr.length - 1].end,
        end: '最大功率',
        duration: '',
      })
    },
    deletePricePower(index) {
      let powerArr = this.fixedPriceArr[index].powerArr
      powerArr.pop()
      powerArr[powerArr.length - 1].end = '最大功率'
    },
    addFixedPrice() {
      let powerPriceArr = _.cloneDeep(
        this.fixedPriceArr[this.fixedPriceArr.length - 1].powerArr
      )
      _.each(powerPriceArr, (item) => {
        item.duration = ''
      })
      this.fixedPriceArr.push({
        price: '',
        powerArr: powerPriceArr,
      })
    },
    deleteFixedPrice(index) {
      if (this.fixedPriceArr.length === 1) {
        this.$message('至少保留一个固定价格！')
        return
      } else {
        this.fixedPriceArr.splice(index, 1)
      }
    },

    addPrice() {
      this.priceArr[this.priceArr.length - 1].endTime = ''
      this.priceArr.push({
        startTime: this.priceArr[this.priceArr.length - 1].endTime,
        endTime: '24:00',
        price: '',
      })
    },
    deletePrice() {
      this.priceArr.pop()
      this.priceArr[this.priceArr.length - 1].endTime = '24:00'
    },
    handleAddTimeCard() {
      this.timecardVisible = true
      this.timecardArr.push({
        availableDay: '',
        hour: '',
        price: '',
      })
      this.$set(this.priceForm, 'timecardPowerCharging', false)
    },
    addTimecard() {
      this.timecardArr.push({
        availableDay: '',
        hour: '',
        price: '',
      })
    },
    deleteTimecard() {
      this.timecardArr.pop()
      this.timecardVisible = !!this.timecardArr.length
      !this.timecardArr.length && delete this.priceForm.timecardPowerCharging
    },
    handleInput(item, index) {
      this.powerArr[index + 1].start = item.end
      if (item.end <= item.start) {
        this.$message('大功率不能小于等于小功率！')
      }
    },
    handlePowerInput(itemChild, indexChild, index) {
      this.powerStartCurrent = itemChild.start
      this.fixedPriceArr[index].powerArr[indexChild + 1].start = itemChild.end
    },
    handelTimeInput(item, index) {
      this.priceArr[index + 1].startTime = item.endTime
    },
    handlePowerArr() {
      let ladderPower = [0]
      let ladderPrice = []
      this.powerArr.forEach((item, index) => {
        ladderPrice.push(item.price)
        if (index !== this.powerArr.length - 1) ladderPower.push(item.end)
      })
      return {
        ladderPower: ladderPower.join(','),
        ladderPrice: ladderPrice.join(','),
      }
    },
    handleTimecardArr() {
      return this.timecardArr
        .map((item) => {
          return (
            item.hour +
            ',' +
            item.price +
            (item.availableDay ? ',' + item.availableDay : '')
          )
        })
        .join(';')
    },
    _handleStationTypeValid(type, staPriceType) {
      if (type === 'FREE') {
        return true
      } else if (type === 'TEMPORARY' || type === 'MIX') {
        if (staPriceType === 'DURATION') {
          return !this.powerArr.filter((item) => {
            return !item.end || !item.price
          }).length
        } else if (staPriceType === 'INTERVAL') {
          return !this.priceArr.filter((item) => !item.endTime || !item.price)
            .length
        } else {
          return !this.fixedPriceArr.filter((item) => {
            return (
              !item.price ||
              item.powerArr.filter(
                (itemChild) => !itemChild.end || !itemChild.duration
              ).length
            )
          }).length
        }
      } else if (type === 'MONTHLY') {
        if (staPriceType === 'DURATION') {
          return (
            !this.powerArr.filter((item) => {
              return !item.end || !item.price
            }).length &&
            (!this.timecardVisible ||
              (this.timecardVisible &&
                !this.timecardArr.filter((item) => {
                  return !item.hour || !item.price
                }).length))
          )
        } else if (staPriceType === 'INTERVAL') {
          return !this.priceArr.filter((item) => !item.endTime || !item.price)
            .length
        } else {
          return !this.fixedPriceArr.filter((item) => {
            return (
              !item.price ||
              item.powerArr.filter(
                (itemChild) => !itemChild.end || !itemChild.duration
              ).length
            )
          }).length
        }
      }
    },
    //判断不同电站类型，验证时长卡和功率收费
    handleOk() {
      this.powerStartCurrent = ''
      let validAll
      this.$refs.baseForm.validate((valid) => {
        //基础信息
        let hasDesignatedArea =
          this.area &&
          !!this.area
            .map((item) => item.split(',')[1])
            .filter((item) => this.designatedArea.indexOf(item) > -1).length
        validAll =
          valid &&
          ((Object.keys(this.area).length === 3 && !hasDesignatedArea) ||
            (Object.keys(this.area).length === this.designatedAreaLength &&
              hasDesignatedArea)) &&
          this.checkedPoint

        this.$refs.priceForm.validate((valid) => {
          validAll = valid && validAll
          if (this.priceFormVisible) {
            validAll =
              validAll &&
              !document.getElementsByClassName('input-error').length &&
              this._handleStationTypeValid(
                this.priceForm.stationType,
                this.priceForm.staPriceType
              )
          }
        })
        if (!validAll) {
          this.$message('请检查所有信息是否填写完整')
          return
        }

        if (this.priceForm.staPriceType === 'INTERVAL') {
          //按次收费需要判断最低金额的一半
          if (!this.isElectricServicePrice) {
            //服务费判断
            if (
              new Big(this.priceForm.stationService) * 2 >
              this.priceForm.quotaPrice[0]
            ) {
              this.$confirm(
                '服务费已超过所选择最低预付金额的50%，用户可充电量有限，请调低服务费或增加最高预付金额。',
                '提示',
                {
                  confirmButtonText: '确定',
                  center: true,
                  showCancelButton: false,
                  customClass: 'tip-dialog__wrapper',
                }
              )
              return
            }
          }
        }

        if (
          this.$route.params.id &&
          this.type === 'edit' &&
          this.detailData.stationType !== 'FREE' &&
          this.detailData.staPriceType === 'DURATION' &&
          (this.priceForm.staPriceType === 'INTERVAL' ||
            this.priceForm.staPriceType === 'FIXED')
        ) {
          this.$confirm(
            `请确认是否将电站计费方式设定为按照${
              this.priceForm.staPriceType === 'INTERVAL'
                ? '区间电价计费'
                : '固定价格计费'
            }，设定后原有用户的时长卡套餐将无法在该电站使用。`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              center: true,
              customClass: 'tip-dialog__wrapper',
            }
          )
            .then(() => {
              this.submitFormData()
            })
            .catch((err) => console.log(err))
        } else {
          this.submitFormData()
        }
      })
    },
    submitFormData() {
      // let bdLngLat = toBdMapLngLat(this.checkedPoint)
      let params = {
        ...this.baseForm,
        district: this.area[2].split(',')[0],
        city: this.area[1].split(',')[0],
        province: this.area[0].split(',')[0],
        defAdCode:
          this.area && this.area.length > 3
            ? this.area[this.area.length - 1].split(',')[0]
            : null,
        stationImg: this.baseForm.stationImg,
        stationLat: this.checkedPoint.lat,
        stationLng: this.checkedPoint.lng,
      }
      let priceFormParams = {
        ...this.priceForm,
      }

      //按度收服务费
      if (this.isElectricServicePrice) {
        var service = priceFormParams.stationService
        priceFormParams.electricServicePrice = service
      }
      if (this.priceForm.stationType === 'FREE') {
        //免费电站
        priceFormParams.stationChargeTime =
          this.priceForm.stationChargeTime.join(',')
      } else {
        if (this.priceForm.staPriceType === 'DURATION') {
          priceFormParams.stationChargeTime =
            this.priceForm.stationChargeTime.join(',')
          Object.assign(priceFormParams, {
            ladderPrice: this.handlePowerArr().ladderPrice,
            ladderPower: this.handlePowerArr().ladderPower,
          })
          if (
            this.priceForm.stationType === 'MONTHLY' ||
            this.priceForm.stationType === 'MIX'
          ) {
            Object.assign(
              priceFormParams,
              this.timecardArr.length && {
                timeCardRule: this.handleTimecardArr(),
              }
            )
          }
        } else if (this.priceForm.staPriceType === 'INTERVAL') {
          let priceArr = []
          this.priceArr.forEach((item) => {
            if (priceFormParams.electricServicePrice) {
              // 区间电价按度
              priceArr.push({
                t: item.endTime,
                pr: Number(
                  Number(item.price) +
                    Number(priceFormParams.electricServicePrice)
                ),
                ep: Number(item.price),
                sp: Number(priceFormParams.electricServicePrice),
              })
            } else {
              priceArr.push({
                t: item.endTime,
                pr: Number(item.price),
                ep: Number(item.price),
                sp: 0,
              })
            }
          })
          Object.assign(priceFormParams, {
            priceDscrptJson: JSON.stringify(priceArr),
            quotaPrice: this.priceForm.quotaPrice.join(','),
          })
        } else if (this.priceForm.staPriceType === 'FIXED') {
          let fixedPriceArr = []
          this.fixedPriceArr.forEach((item) => {
            fixedPriceArr.push({
              lpr: item.price,
              spd: item.powerArr.map((item) => {
                return { p: item.start, t: Number(item.duration) }
              }),
            })
          })
          Object.assign(priceFormParams, {
            priceDscrptJson: JSON.stringify(fixedPriceArr),
          })
        }
      }
      //按每小时充电计费
      if (this.isDurationServicePrice) {
        var stationService = priceFormParams.stationService
        priceFormParams.durationServicePrice = stationService
      }

      Object.assign(params, priceFormParams)
      if (this.$route.params.id && this.type === 'edit') {
        Object.assign(params, { id: this.detailData.id })
      } //仅更新的时候传（新增和复制都不传）

      //按度收服务费
      if (this.isElectricServicePrice) {
        params['stationService'] = 0
        params['durationServicePrice'] = 0
      }
      //按每小时充电计费
      if (this.isDurationServicePrice) {
        params['stationService'] = 0
        params['electricServicePrice'] = 0
      }
      //按每小时充电计费
      console.log('0000-', this.isTimesServicePrice)
      if (this.isTimesServicePrice) {
        params['electricServicePrice'] = 0
        params['durationServicePrice'] = 0
      }

      console.log(params)

      createStation(params).then(
        () => {
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.$router.push('/device/stationList')
        },
        (res) => {
          if (res.code === 40030) {
            this._goToCreateAndEnergy()
          }
        }
      )
    },
    reset() {
      if (this.$route.params.id) {
        this.handleBackFill()
        return
      }
      this.baseForm = {
        stationAddress: '',
        stationImg: '',
        hasRemark: false,
        remark: '',
      }
      this.area = []
      this.$refs.stationImg.handleRemove()
      this.tempObj = {
        stationChargeTime: [],
        quotaPrice: [],
      }
      this.priceForm.stationChargeTime = []
      if (this.priceFormVisible) {
        this.timecardVisible = false
        this.priceForm = {
          stationType: this.priceFormVisible ? 'MIX' : 'FREE',
          payType: this.priceFormVisible ? 'PostPay' : null,
          staPriceType: 'DURATION',
          quotaPrice: [],
        }
        this.powerArr = [
          {
            start: '0',
            end: '最大功率',
            price: '',
          },
        ]
        this.timecardArr = []
        this.priceArr = [
          {
            startTime: '00:00',
            endTime: '24:00',
            price: '',
          },
        ]
        this.fixedPriceArr = [
          {
            price: '',
            powerArr: [
              {
                start: '0',
                end: '最大功率',
                duration: '',
              },
            ],
          },
        ]
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.i-form {
  padding: 0 40px;
  &::v-deep .el-form-item__content {
    width: 50%;
  }
  .duration-item {
    &::v-deep .el-form-item__content {
      width: 100%;
    }
  }
  .timecard-item {
    &::v-deep .el-form-item__content {
      width: 75%;
    }
  }
  .item-tip {
    color: #9d9d9d;
    &::before {
      content: '*';
      color: #ff4d4f;
    }
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel__body .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #d9d9d9;
  }
  &::v-deep .el-checkbox-button__inner {
    border: 1px solid #d6d8e0;
    margin-right: 10px;
    width: 88px;
    height: 36px;
    line-height: 36px;
    padding: 0;
    box-shadow: none !important;
  }
  &::v-deep .el-checkbox-button:last-child .el-checkbox-button__inner {
    margin-right: 0;
  }
  &::v-deep .is-checked .el-checkbox-button__inner {
    border-color: #e9f3ff;
    color: #005be5;
    background: #e9f3ff;
  }
  &::v-deep .el-form .el-date-editor {
    width: 120px !important;
  }

  &::v-deep .el-form .el-input__prefix {
    height: 40px;
  }
}
.timecard-charging {
  margin-top: 8px;
  display: flex;
  align-items: center;
  height: 100%;
}
.timecard-charging__img {
  width: 20px;
  margin-left: 10px;
  cursor: pointer;
}
.show-tip {
  color: #5daa45;
  font-size: 12px;
  line-height: 20px;
}
.power-wrapper {
  display: flex;
  background: #f7f1fc;
  justify-content: space-between;
  padding: 22px 24px;
  .power-input-price {
    width: 120px;
    margin-bottom: 10px;
  }
  .power-input__item {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 24px;
    flex: 1 1 auto;
    align-items: flex-start;
    &:last-child {
      margin-bottom: 0;
    }
    .el-input {
      width: 120px;
      &:last-child {
        margin-left: 20px;
      }
    }
    .line {
      width: 80px;
      border-top: 1px dotted #d6d8e0;
      vertical-align: middle;
      margin: 0 5px;
      margin-top: 19px;
    }
  }
}
.timecard-wrapper {
  display: flex;
  justify-content: space-between;
  background: #f7f1fc;
  padding: 22px 24px;
  .timecard-input__item {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 24px;
    flex: 1 1 auto;
    &:last-child {
      margin-bottom: 0;
    }
    .timecard-input__cell {
      display: flex;
      .el-input {
        width: 120px;
      }
    }
  }
}
.btn {
  color: red;
  align-self: flex-end;
  [class^='el-icon-'] {
    font-size: 20px;
  }
  .el-icon-circle-plus {
    color: blue;
    margin-left: 5px;
  }
}
.description-statement {
  color: #9d9d9d;
  padding: 4px 40px 20px;
}
.fixedPrice-wrapper {
  display: flex;
  justify-content: space-between;
  background: #f7f1fc;
  padding: 22px 24px;

  &:not(:first-child) {
    border-top: 1px dashed #d6d8e0;
  }
  .fixedPrice__item {
    .fixedPrice-input-price {
      width: 120px;
      margin-bottom: 10px;
      vertical-align: top;
    }
    .fixedPrice-input-power {
      display: flex;
      justify-content: space-between;
      .power-input__item {
        display: flex;
        flex-wrap: wrap;
        flex: 1 1 auto;
        align-items: flex-start;
        margin-bottom: 10px;
        &:last-child {
          margin-bottom: 0;
        }
        .el-input {
          width: 120px;
          &:last-child {
            margin-left: 20px;
          }
        }
        .line {
          width: 80px;
          border-top: 1px dotted #d6d8e0;
          vertical-align: middle;
          margin: 0 5px;
          margin-top: 19px;
        }
      }
    }
  }
}
</style>
